package com.mobi.Survey.lib.activities;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.mobi.Survey.lib.R;
import com.mobi.Survey.lib.db.AbstractTable;
import com.mobi.Survey.lib.db.AlarmTable;
import com.mobi.Survey.lib.db.SurveyDetailTable;
import com.mobi.Survey.lib.model.AlarmPojo;
import com.mobi.Survey.lib.model.SurveyDetailPojo;
import com.mobi.Survey.lib.model.SurveyPojo;
import com.mobi.Survey.lib.model.SurveyResultPojo;

public class TimerListScreen extends AbstractScreen {

	private ListView lvTimers;
	private CustomAdapterTimerList adapter;
	private TextView tvAlarmCount;
	private CheckBox cbSelectAll;
	private View btnDelete;
	private List<AlarmPojo> alarms;

	private int alarmSize;
	private long surveyId;
	private boolean isLongClicked;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		lvTimers.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long arg3) {
				isLongClicked = true;
				AlarmPojo alarm = (AlarmPojo) adapter.getItem(position);
				selectDeselectItem(view, alarm);

				return true;
			}
		});

		lvTimers.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {

				AlarmPojo alarm = (AlarmPojo) adapter.getItem(position);

				if (!isLongClicked) {
					openAlarmScreen(alarm);
				} else {

					selectDeselectItem(view, alarm);
				}

			}

		});
		cbSelectAll.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				onSelectAllButtonClick();

			}
		});
		getExtras();
		initTimerList();

		if (alarmSize == 0) {
			new LongTask().execute();
		}

		

	}

	private void selectDeselectItem(View view, AlarmPojo alarm) {

		if (view.getBackground() == null) {

			view.setBackgroundDrawable(getResources().getDrawable(R.drawable.item_bg));

			adapter.getSelectedAlarms().add(alarm);

		} else {
			view.setBackgroundDrawable(null);
			if (adapter.getSelectedAlarms().size() > 0)
				adapter.getSelectedAlarms().remove(alarm);

		}

		int selectedSize = adapter.getSelectedAlarms().size();

		if (alarmSize == selectedSize) {
			if (btnDelete.getVisibility() == View.INVISIBLE) {
				btnDelete.setVisibility(View.VISIBLE);
			}
			if (!cbSelectAll.isChecked()) {
				cbSelectAll.setChecked(true);
			}
		}

		if (selectedSize < alarmSize && selectedSize > 0) {
			if (cbSelectAll.isChecked()) {
				cbSelectAll.setChecked(false);
			}
			if (btnDelete.getVisibility() == View.INVISIBLE) {
				btnDelete.setVisibility(View.VISIBLE);
			}
		}
		if (alarmSize == 0) {
			if (btnDelete.getVisibility() != View.INVISIBLE) {
				btnDelete.setVisibility(View.INVISIBLE);
			}
			if (cbSelectAll.getVisibility() != View.INVISIBLE) {
				cbSelectAll.setVisibility(View.INVISIBLE);
			}
		}
		if (selectedSize == 0) {
			if (btnDelete.getVisibility() != View.INVISIBLE) {
				btnDelete.setVisibility(View.INVISIBLE);
			}
			if (cbSelectAll.isChecked()) {
				cbSelectAll.setChecked(false);
			}
		}

	}

	private void openAlarmScreen(AlarmPojo alarm) {

		Map<String, Object> extras = new HashMap<String, Object>();
		extras.put("attributes", alarm);
		extras.put("timerListScreen", Boolean.TRUE);

		switchScreenTo(AlarmScreen.class, extras);
	}

	private void getExtras() {
		Intent intent = getIntent();
		surveyId = intent.getExtras().getLong("data");
	}

	private void initTimerList() {
		AlarmTable alarmTable = new AlarmTable(this);

		alarms = alarmTable.getValidAlarmBySurveyId(surveyId);
		alarmSize = alarms.size();
		alarmTable.closeDB();

		adapter = new CustomAdapterTimerList(this, alarms);
		lvTimers.setAdapter(adapter);
		
		tvAlarmCount.setText(alarmSize + " Item" + (alarmSize > 0 ? "s" : ""));

	}

	private void onSelectAllButtonClick() {
		if (alarmSize == 0) {
			return;
		}
		if (cbSelectAll.isChecked()) {
			adapter.toggleSelectAll(true);
			btnDelete.setVisibility(View.VISIBLE);
		} else {
			adapter.toggleSelectAll(false);
			btnDelete.setVisibility(View.INVISIBLE);
		}

	}

	@Override
	protected void initUiVars() {
		lvTimers = (ListView) findViewById(R.id.lvTimers);
		tvAlarmCount = (TextView) findViewById(R.id.tvAlarmCount);
		cbSelectAll = (CheckBox) findViewById(R.id.cbSelectAll);
		btnDelete = findViewById(R.id.btnDelete);

	}

	public void onClick(View v) {
		showDeleteConfirmation();

	}

	@Override
	protected int getLayoutId() {

		return LayoutIds.TIMER_LIST_SCREEN;
	}

	@Override
	protected void onRelease() {

	}

	private void showDeleteConfirmation() {

		final AlertDialog.Builder alert = new AlertDialog.Builder(TimerListScreen.this);

		alert.setTitle(Messages.ARE_YOU_SURE);
		alert.setMessage(Messages.ALARM_WILL_BE_DELETE);

		alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				new DeleteAlarmTask().execute();
			}
		});

		alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {

			}
		});
		alert.show();

	}

	private void onDeleteTaskExecuted() {
		alarmSize = alarms.size();
		btnDelete.setVisibility(View.INVISIBLE);
		if (alarmSize == 0) {
			cbSelectAll.setVisibility(View.INVISIBLE);
		} else {
			cbSelectAll.setChecked(false);
		}

	}

	private class DeleteAlarmTask extends AsyncTask<Integer, Integer, Integer> {
		ProgressDialog progressDialog = null;

		@Override
		protected void onPreExecute() {

			super.onPreExecute();

			progressDialog = ProgressDialog.show(TimerListScreen.this, "", Messages.DELETE_ALARM);

		}

		@Override
		protected void onPostExecute(Integer remaining) {

			super.onPostExecute(remaining);
			adapter.notifyDataSetChanged();

			tvAlarmCount.setText(remaining + " Item" + (remaining > 0 ? "s" : ""));
			onDeleteTaskExecuted();

			progressDialog.dismiss();

		}

		@Override
		protected Integer doInBackground(Integer... input) {
			AlarmTable table = new AlarmTable(TimerListScreen.this);
			int deleteCount = 0;
			alarmSize = alarms.size();
			for (AlarmPojo alarm : adapter.getSelectedAlarms()) {

				boolean deleted = table.deleteRow(alarm.getId());
				adapter.removeItem(alarm);
				if (deleted)
					deleteCount++;
			}

			table.closeDB();
			adapter.getSelectedAlarms().clear();
			return alarmSize - deleteCount;
		}
	}

	private class LongTask extends AsyncTask<Long, Integer, Object> {
		ProgressDialog progressDialog = null;

		protected Object doInBackground(Long... params) {

			AbstractTable at = new SurveyDetailTable(getApplicationContext());

			List<SurveyDetailPojo> sdps = ((SurveyDetailTable) at).getSurveyDetail(surveyId);

			if (sdps.size() == 0) {
				try {
					SurveyPojo downloaded = downloadSurveyDetail(surveyId);
					sdps = downloaded.getSurveyDetail();
					SurveyDetailPojo.commit(getApplicationContext(), sdps, surveyId);

					List<AlarmPojo> alarms = downloaded.getAlarms();

					for (AlarmPojo saveAlarm : alarms) {
						saveAlarm.setSurveyId(surveyId);

						AlarmPojo.commit(saveAlarm, getApplicationContext());
					}

					AlarmTable tb = new AlarmTable(getApplicationContext());
					List<AlarmPojo> futureALarms = tb.getUpComings();

					setupAlarms(futureALarms);

					tb.closeDB();
					
					

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				}
			}

			at.closeDB();
			SurveyResultPojo.writeSurveyResult(surveyId, sdps, getApplicationContext());

			return null;

		}

		protected void onPostExecute(Object result) {

			super.onPostExecute(result);
			initTimerList();
			progressDialog.dismiss();
			progressDialog = null;

		}

		protected void onPreExecute() {

			super.onPreExecute();
			try {
				progressDialog = ProgressDialog.show(TimerListScreen.this, "", "Loading Alarms");
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	private void deSelectOnBackPress() {
		adapter.toggleSelectAll(false);
		cbSelectAll.setChecked(false);
		btnDelete.setVisibility(View.INVISIBLE);
		isLongClicked = false;
	}

	@Override
	public void onBackPressed() {
		if (isLongClicked) {
			deSelectOnBackPress();
		} else {
			super.onBackPressed();
		}

	}

}
